﻿using NPoco;
using System;
using System.Configuration;

namespace Beginner.Infrastructure.Helper
{
    /// <summary>
    /// 数据库帮助类
    /// </summary>
    public class DbHelper : IDisposable
    {
        private static readonly string DbConnectionName = ConfigurationManager.AppSettings["DbConnectionName"];

        private IDatabase _dbBase ;
        private static DbHelper _helper;
        private static object _helpLock = new object();

        //单例
        private DbHelper()
        {
        }
        /// <summary>
        /// 获取类的实例
        /// </summary>
        public static DbHelper Instance
        {
            get
            {
                lock (_helpLock)
                {
                    if (_helper != null)
                        return _helper;
                    _helper = new DbHelper();
                    return _helper;
                }
            }
        }
        /// <summary>
        /// 获取当前配置的数据库访问对象上下文
        /// </summary>
        public IDatabase CurrentContext
        {
            get
            {
                return _dbBase ?? new Database(DbConnectionName ?? "DefaultConnectionString");
            }
        }
        /// <summary>
        /// 获取新数据库访问对象上下文
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public IDatabase GetNewDbContext(string connectionString)
        {
            return new Database(connectionString);
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            _dbBase.Dispose();
        }
    }
}
